<?php
namespace app\common\server;
use x\Xbase;
class Withdraw extends Xbase{

    /**
     * 提现申请
     * @param [type] $user_id    [description]
     * @param [type] $money      [description]
     * @param [type] $money_type [description]
     * @param [type] $bank_id    [description]
     * @param [type] $sys        [description]
     */
    public function add($user_id,$money,$money_type,$bank_name,$bank_username,$bank_area,$bank_no,$sys){
        $user = $this->db->find('user',$user_id);
        if ($money <= 0) return $this->setError('金额错误');
        if ($money>$user[$money_type]) return $this->setError('余额不足');

        $order_no = $this->com_order_no();
        
        $this->db->begin();
        $mysql = [];

        $fee = 0;
        if(!empty($sys['service_fee'])){
            $fee = bcmul($money,$sys['service_fee'],2);
            $fee = bcdiv($fee,100,2);
        }
        $data = [
            "user_id" => $user_id,
            "money" => $money,
            "money_type" => $money_type,
            "fee" => $fee,
            "real_money" => bcsub($money,$fee,2),
            "create_time" => time(),
            "order_no" => $order_no,
            "bank_username" => $bank_username,
            "bank_name" => $bank_name,
            "bank_area" => $bank_area,
            "bank_no" => $bank_no,
        ];
        $mysql[] = $id = $this->db->insert("withdraw",$data);

        $mysql[] = m('Userbill','xcom')->doit($order_no,$user_id,202,'withdraw',$id,$data['money'],$money_type,"申请提现");

        $rs = $this->db->end($mysql);
        if(!$rs) return $this->setError('申请提现失败');
        return true;
    }

    public function close($id,$note=""){
        $info = $this->db->find('withdraw',$id);
        if(!$info){
            return $this->setError('数据没找到');
        }
        if($info["status"] != 0 && $info["daifa_status"] != 0 && $info["shenhe_status"] != 0){
            return $this->setError('该数据不能变动');
        }
        $this->db->begin();
        $mysql = [];
        $mysql[] = $this->db->update("withdraw",['status'=>1,'shenhe_status'=>1,'shenhe_status_note'=>$note,'id'=>$id]);
        $mysql[] = m('Userbill','xcom')->doit($info['order_no'], $info['user_id'], 106, 'withdraw', $id,  $info['money'],$info['money_type'],'驳回提现');
        $rs = $this->db->end($mysql);
        if(!$rs){
            return $this->setError('关闭失败');
        }else{
            return true;
        }
    }

}
